/** @jsxRuntime classic */
/** @jsx jsxCustomEvent */
import microApp from '@micro-zoe/micro-app';
import React, { forwardRef, useImperativeHandle } from 'react';
import type { BasicMicroAppProps, MicroAppRef } from '../../types';
import jsxCustomEvent from '@micro-zoe/micro-app/polyfill/jsx-custom-event';
// 类型定义已合并到 types/index.ts 中

/**
 * 基础微应用组件
 *
 * 功能特性：
 * - 完全透传所有官方属性和事件
 * - 提供基础的加载状态管理
 * - 支持自定义样式和类名
 * - 提供 TypeScript 类型支持
 * - 100% 兼容官方 API
 */
const BasicMicroApp = forwardRef<MicroAppRef, BasicMicroAppProps>(
  (
    {
      // 官方属性 - 必须完全透传
      name,
      url,
      routerMode = 'pure',
      defaultPage,
      keepAlive,
      iframe,
      inline,
      disableScopecss,
      disableSandbox,
      disableMemoryRouter,
      keepRouterState,
      disablePatchRequest,
      destroy,
      fiber,
      baseroute,
      ssr,
      data,
      lifeCycles,

      // 官方事件 - 必须完全透传
      onCreated,
      onBeforemount,
      onMounted,
      onUnmount,
      onError,
      onBeforeshow,
      onAftershow,
      onAfterhidden,
      onDataChange,

      // 扩展属性
      loading,
      className,
      style,
      ...rest
    },
    ref,
  ) => {
    // 暴露给父组件的方法
    useImperativeHandle(ref, () => ({
      reload: () => {
        console.log(`重新加载微应用: ${name}`);
        microApp.reload(name, true);
      },
    }));

    // 构建微应用属性
    const microAppProps: any = {
      name,
      url,
      // 只有在值存在时才设置属性，避免传递 undefined
      ...(routerMode && { 'router-mode': routerMode }),
      ...(defaultPage && { 'default-page': defaultPage }),
      ...(keepAlive !== undefined && { 'keep-alive': keepAlive }),
      ...(iframe !== undefined && { iframe }),
      ...(inline !== undefined && { inline }),
      ...(disableScopecss !== undefined && {
        'disable-scopecss': disableScopecss,
      }),
      ...(disableSandbox !== undefined && {
        'disable-sandbox': disableSandbox,
      }),
      ...(disableMemoryRouter !== undefined && {
        'disable-memory-router': disableMemoryRouter,
      }),
      ...(keepRouterState !== undefined && {
        'keep-router-state': keepRouterState,
      }),
      ...(disablePatchRequest !== undefined && {
        'disable-patch-request': disablePatchRequest,
      }),
      ...(destroy !== undefined && { destroy }),
      ...(fiber !== undefined && { fiber }),
      ...(baseroute && { baseroute }),
      ...(ssr !== undefined && { ssr }),
      ...(data && { data }),
    };

    // 处理生命周期事件
    if (lifeCycles) {
      Object.entries(lifeCycles).forEach(([key, handler]) => {
        if (handler) {
          microAppProps[key] = handler;
        }
      });
    }

    // 组件样式
    const componentStyle: React.CSSProperties = {
      display: 'block',
      width: '100%',
      height: '100%',
      ...style,
    };

    return (
      <div className={className} style={componentStyle}>
        <micro-app
          {...microAppProps}
          onCreated={(event: CustomEvent) => {
            console.log('micro-app元素被创建');
            if (onCreated) onCreated(event);
          }}
          onBeforemount={(event: CustomEvent) => {
            console.log('即将被渲染，只在初始化时执行一次');
            if (onBeforemount) onBeforemount(event);
          }}
          onMounted={(event: CustomEvent) => {
            console.log('已经渲染完成，只在初始化时执行一次');
            if (onMounted) onMounted(event);
          }}
          onUnmount={(event: CustomEvent) => {
            console.log('已经卸载');
            if (onUnmount) onUnmount(event);
          }}
          onError={(event: CustomEvent) => {
            console.error('微应用加载错误:', event);
            if (onError) onError(event);
          }}
          onBeforeshow={(event: CustomEvent) => {
            console.log('即将推入前台，初始化时不执行');
            if (onBeforeshow) onBeforeshow(event);
          }}
          onAftershow={(event: CustomEvent) => {
            console.log('已经推入前台，初始化时不执行');
            if (onAftershow) onAftershow(event);
          }}
          onAfterhidden={(event: CustomEvent) => {
            console.log('已推入后台');
            if (onAfterhidden) onAfterhidden(event);
          }}
          onDataChange={(event: CustomEvent) => {
            console.log('来自子应用的数据：', event.detail?.data);
            if (onDataChange) onDataChange(event);
          }}
          {...rest}
        />
        {loading && (
          <div
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              backgroundColor: 'rgba(255, 255, 255, 0.8)',
              zIndex: 1000,
            }}
          >
            {typeof loading === 'boolean' ? <div>加载中...</div> : loading}
          </div>
        )}
      </div>
    );
  },
);

BasicMicroApp.displayName = 'BasicMicroApp';

export default BasicMicroApp;
